package com.gxa.ssm251.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.gxa.ssm251.pojo.Order;

import com.gxa.ssm251.service.OrderService;

import com.gxa.ssm251.util.JsonResult;
import io.swagger.annotations.Api;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/excle")
@Api(value = "执行导出功能控制器", tags = "订单导出接口的api")
@CrossOrigin //跨域的注解
public class ExcleController {

    @Resource
    private OrderService orderService;

    @RequestMapping("toExportDone")
    @ResponseBody
    public String exportDo(HttpServletResponse response) {
        response.setContentType("application/binary;charset=UTF-8");
        try {
            ServletOutputStream out = response.getOutputStream();
            String fileName = new String((new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), "UTF-8");
//            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
//            response.setHeader("Content-disposition", "attachment; filename=" + "老王" + ".xls");
            String fileName1 = "订单导出列表.xls";
            String fileName2 = URLEncoder.encode(fileName1, "utf-8").replaceAll("\\+", "%20");
//            response.setHeader("Content-disposition", "attachment;filename="  + fileName2);
//            response.setHeader("Content-Disposition", "attachment;filename="  + URLEncoder.encode("老王.xls", "UTF-8"));

            fileName = URLEncoder.encode(fileName1, StandardCharsets.UTF_8.toString());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());


// 解决中文文件名乱码关键行
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"; filename*=utf-8''" + fileName);


//            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName1.getBytes("gbk"),"ISO-8859-1"));
            String[] titles = {"订单编号", "订单类型", "姓名", "城市", "订单来源", "手机号", "车牌号", "接车司机",
                    "是否还车", "还车司机", "订单状态", "下单时间", "付款状态"};
            export(titles, out);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "导出信息失败";
        }
    }

    public void export(String[] titles, ServletOutputStream out) {
        // 1.创建一个workbook，对应一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 2.在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet hssfSheet = workbook.createSheet("sheet1");
        // 3.在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow hssfRow = hssfSheet.createRow(0);
        // 4.创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle hssfCellStyle = workbook.createCellStyle();
        //居中样式
        hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCell hssfCell = null;
        for (int i = 0; i < titles.length; i++) {
            hssfCell = hssfRow.createCell(i);//列索引从0开始
            hssfCell.setCellValue(titles[i]);//列名1
            hssfCell.setCellStyle(hssfCellStyle);//列居中显示
        }

        // 5.写入实体数据
        List<Order> users = orderService.selectAllOrder();//查询所有的用户
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (users.size() > 0) {
            for (int i = 0; i < users.size(); i++) {
                hssfRow = hssfSheet.createRow(i + 1);
                Order user = users.get(i);

                // 6.创建单元格，并设置值
                String userid = "";
                if (user.getId() != null) {
                    userid = user.getId().toString();
                }
                hssfRow.createCell(0).setCellValue(userid);
                String type = "";
                if (user.getType() != null) {
                    type = user.getType();
                }
                hssfRow.createCell(1).setCellValue(type);
                String name = "";
                if (user.getUserName() != null) {
                    name = user.getUserName();
                }
                hssfRow.createCell(2).setCellValue(name);

                String city = "";
                if (user.getCityName() != null) {
                    city = user.getCityName();
                }
                hssfRow.createCell(3).setCellValue(city);

                String origin = "";
                if (user.getOrigin() != null) {
                    origin = user.getOrigin();
                }
                hssfRow.createCell(4).setCellValue(origin);

                String phone = "";
                if (user.getUserPhone() != null) {
                    phone = user.getUserPhone();
                }
                hssfRow.createCell(5).setCellValue(phone);

                String carNumber = "";
                if (user.getCarNumber() != null) {
                    carNumber = user.getCarNumber();
                }
                hssfRow.createCell(6).setCellValue(carNumber);

                String carBringName = "";
                if (user.getCarBringName() != null) {
                    carBringName = user.getCarBringName();
                }
                hssfRow.createCell(7).setCellValue(carBringName);

                String inBack = "";
                if (user.getInBack() != null) {
                    inBack = user.getInBack().toString();
                }
                hssfRow.createCell(8).setCellValue(inBack);

                String carBackName = "";
                if (user.getCarBackName() != null) {
                    carBackName = user.getCarBackName();
                }
                hssfRow.createCell(9).setCellValue(carBackName);

                String status = "";
                if (user.getStatus() != null) {
                    status = user.getStatus();
                }
                hssfRow.createCell(10).setCellValue(status);

                Date time = null;
                if (user.getTime() != null) {
                    time = user.getTime();
                }
                hssfRow.createCell(11).setCellValue(sdf.format(time));

                String order_inPay = "";
                if (user.getInPay() != null) {
                    order_inPay = user.getInPay().toString();
                }
                hssfRow.createCell(12).setCellValue(order_inPay);


            }
        }
        // 7.将文件输出到客户端浏览器
        try {
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}